package com.hifar.sso.controller;

import com.hifar.sso.model.SSORequest;
import com.hifar.sso.model.SSOResponse;
import com.hifar.sso.model.SSOUser;
import com.hifar.sso.service.SSOAuthService;
import com.hifar.sso.util.SSOConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * SSO登录控制器
 *
 * @author system
 * @since 1.0.0
 */
@Controller
@RequestMapping("/sso")
public class SSOLoginController {

    private static final Logger logger = LoggerFactory.getLogger(SSOLoginController.class);

    @Autowired
    private SSOAuthService ssoAuthService;

    /**
     * 测试中文编码接口
     */
    @GetMapping("/test/encoding")
    @ResponseBody
    public String testEncoding(HttpServletResponse response) {
        // 强制设置编码
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        return "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>编码测试</title></head>" +
               "<body><h1>中文编码测试</h1><p>如果你能看到正确的中文，说明编码配置正常。</p>" +
               "<p>测试内容：单点登录、用户名、密码、登录按钮</p>" +
               "<p>当前时间：" + new java.util.Date() + "</p></body></html>";
    }

    /**
     * 简单中文测试接口
     */
    @GetMapping("/test/simple")
    public void testSimple(HttpServletResponse response) throws java.io.IOException {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Content-Type", "text/plain;charset=UTF-8");

        String content = "中文测试：单点登录系统\n用户名：admin\n密码：123456\n登录状态：正常";
        response.getWriter().write(content);
        response.getWriter().flush();
    }


    /**
     * 手动解析参数的工具方法
     */
    private java.util.Map<String, String> parseFormData(String formData) {
        java.util.Map<String, String> params = new java.util.HashMap<>();
        if (formData != null && !formData.trim().isEmpty()) {
            String[] pairs = formData.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=", 2);
                if (keyValue.length == 2) {
                    try {
                        String key = java.net.URLDecoder.decode(keyValue[0], "UTF-8");
                        String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                        params.put(key, value);
                    } catch (Exception e) {
                        // 忽略解码错误
                    }
                }
            }
        }
        return params;
    }

    /**
     * 显示登录页面
     *
     * @param clientId 客户端ID
     * @param responseType 响应类型
     * @param redirectUri 重定向URI
     * @param scope 作用域
     * @param state 状态参数
     * @param response HTTP响应
     * @return 登录页面HTML
     */
    @GetMapping("/login")
    public void loginPage(
            @RequestParam(value = "client_id", defaultValue = "test") String clientId,
            @RequestParam(value = "response_type", defaultValue = "code") String responseType,
            @RequestParam(value = "redirect_uri", defaultValue = "http://localhost:8080/callback") String redirectUri,
            @RequestParam(value = "scope", required = false) String scope,
            @RequestParam(value = "state", required = false) String state,
            HttpServletResponse response) throws java.io.IOException {

        logger.info("显示登录页面，客户端ID: {}", clientId);

        // 强制设置响应编码 - 确保中文正确显示
        response.reset();
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("X-Content-Type-Options", "nosniff");

        String html = generateLoginPage(clientId, responseType, redirectUri, scope, state);
        byte[] bytes = html.getBytes("UTF-8");
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
    }

    /**
     * 处理登录请求（页面表单提交）
     *
     * @param username 用户名
     * @param password 密码
     * @param clientId 客户端ID
     * @param responseType 响应类型
     * @param redirectUri 重定向URI
     * @param scope 作用域
     * @param state 状态参数
     * @param request HTTP请求
     * @param response HTTP响应
     * @return 登录结果
     */
    @PostMapping("/login")
    public void login(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "client_id", required = false) String clientId,
            @RequestParam(value = "response_type", required = false) String responseType,
            @RequestParam(value = "redirect_uri", required = false) String redirectUri,
            @RequestParam(value = "scope", required = false) String scope,
            @RequestParam(value = "state", required = false) String state,
            HttpServletRequest request,
            HttpServletResponse response,
            Model model) throws IOException {

        try {
            // 记录原始参数
            logger.info("原始@RequestParam参数 - username: {}, password: {}, clientId: {}, responseType: {}, redirectUri: {}",
                       username, password, clientId, responseType, redirectUri);

            // 记录请求信息
            logger.info("请求信息 - ContentType: {}, Method: {}, URI: {}",
                       request.getContentType(), request.getMethod(), request.getRequestURI());

            // 手动解析请求体参数
            StringBuilder requestBody = new StringBuilder();
            try (java.io.BufferedReader reader = request.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            } catch (Exception e) {
                logger.error("读取请求体失败: {}", e.getMessage());
            }

            logger.info("原始请求体: {}", requestBody.toString());

            // 手动解析参数
            java.util.Map<String, String> manualParams = parseFormData(requestBody.toString());
            logger.info("手动解析参数: {}", manualParams);

            // 优先使用手动解析的参数
            if (manualParams.containsKey("username")) {
                username = manualParams.get("username");
                logger.info("从手动解析获取username: {}", username);
            } else if (username == null || username.trim().isEmpty()) {
                username = request.getParameter("username");
                logger.info("从request.getParameter获取username: {}", username);
            }

            if (manualParams.containsKey("password")) {
                password = manualParams.get("password");
                logger.info("从手动解析获取password: {}", password);
            } else if (password == null || password.trim().isEmpty()) {
                password = request.getParameter("password");
                logger.info("从request.getParameter获取password: {}", password);
            }

            if (manualParams.containsKey("client_id")) {
                clientId = manualParams.get("client_id");
                logger.info("从手动解析获取clientId: {}", clientId);
            } else if (clientId == null || clientId.trim().isEmpty()) {
                clientId = request.getParameter("client_id");
                logger.info("从request.getParameter获取clientId: {}", clientId);
            }

            if (manualParams.containsKey("response_type")) {
                responseType = manualParams.get("response_type");
                logger.info("从手动解析获取responseType: {}", responseType);
            } else if (responseType == null || responseType.trim().isEmpty()) {
                responseType = request.getParameter("response_type");
                logger.info("从request.getParameter获取responseType: {}", responseType);
            }

            if (manualParams.containsKey("redirect_uri")) {
                redirectUri = manualParams.get("redirect_uri");
                logger.info("从手动解析获取redirectUri: {}", redirectUri);
            } else if (redirectUri == null || redirectUri.trim().isEmpty()) {
                redirectUri = request.getParameter("redirect_uri");
                logger.info("从request.getParameter获取redirectUri: {}", redirectUri);
            }

            if (manualParams.containsKey("scope")) {
                scope = manualParams.get("scope");
                logger.info("从手动解析获取scope: {}", scope);
            } else if (scope == null || scope.trim().isEmpty()) {
                scope = request.getParameter("scope");
                logger.info("从request.getParameter获取scope: {}", scope);
            }

            if (manualParams.containsKey("state")) {
                state = manualParams.get("state");
                logger.info("从手动解析获取state: {}", state);
            } else if (state == null || state.trim().isEmpty()) {
                state = request.getParameter("state");
                logger.info("从request.getParameter获取state: {}", state);
            }

            logger.info("处理登录请求，用户名: {}, 客户端ID: {}", username, clientId);
            logger.info("请求参数 - responseType: {}, redirectUri: {}, scope: {}, state: {}",
                       responseType, redirectUri, scope, state);

            // 参数验证
            if (username == null || username.trim().isEmpty()) {
                logger.error("用户名参数为空，手动解析参数: {}", manualParams);
                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Content-Type", "text/html;charset=UTF-8");

                String errorHtml = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>参数错误</title></head>" +
                                 "<body><h1>参数错误</h1><p>用户名不能为空</p>" +
                                 "<p>请检查参数传递是否正确</p>" +
                                 "<p>手动解析参数: " + manualParams.toString() + "</p>" +
                                 "<p>原始请求体: " + requestBody.toString() + "</p>" +
                                 "<a href='/sso/test/manual'>点击这里进行参数测试</a>" +
                                 "</body></html>";
                byte[] errorBytes = errorHtml.getBytes("UTF-8");
                response.setContentLength(errorBytes.length);
                response.getOutputStream().write(errorBytes);
                response.getOutputStream().flush();
                return;
            }
            if (password == null || password.trim().isEmpty()) {
                logger.error("密码参数为空，手动解析参数: {}", manualParams);
                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Content-Type", "text/html;charset=UTF-8");

                String errorHtml = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>参数错误</title></head>" +
                                 "<body><h1>参数错误</h1><p>密码不能为空</p>" +
                                 "<p>请检查参数传递是否正确</p>" +
                                 "<p>手动解析参数: " + manualParams.toString() + "</p>" +
                                 "<p>原始请求体: " + requestBody.toString() + "</p>" +
                                 "<a href='/sso/test/manual'>点击这里进行参数测试</a>" +
                                 "</body></html>";
                byte[] errorBytes = errorHtml.getBytes("UTF-8");
                response.setContentLength(errorBytes.length);
                response.getOutputStream().write(errorBytes);
                response.getOutputStream().flush();
                return;
            }
            if (clientId == null || clientId.trim().isEmpty()) {
                clientId = "default";
            }
            if (responseType == null || responseType.trim().isEmpty()) {
                responseType = "code";
            }
            if (redirectUri == null || redirectUri.trim().isEmpty()) {
                redirectUri = "http://localhost:8080/callback";
            }

            // 创建认证请求
            SSORequest ssoRequest = new SSORequest(username, password);
            ssoRequest.setRedirectUri(redirectUri);
            ssoRequest.setClientId(clientId);
            ssoRequest.setClientSecret(clientId);
            // 执行认证
            SSOResponse authResponse = ssoAuthService.authenticate(ssoRequest);

            if (authResponse.isSuccess()) {
                // 认证成功，建立会话
                HttpSession session = request.getSession();
                session.setAttribute("user", authResponse.getUser());
                session.setAttribute("clientId", clientId);

                // 生成授权码
                String code = ssoAuthService.generateAuthorizationCode(ssoRequest);

                // 重定向到客户端
                String redirectUrl = redirectUri + "?code=" + code + "&username=" + username;
                if (state != null) {
                    redirectUrl += "&state=" + state;
                }

                logger.info("登录成功，重定向到: {}", redirectUrl);
                response.sendRedirect(redirectUrl);
                return;

            } else {
                // 认证失败，返回登录页面
                logger.warn("登录失败，用户名: {}, 错误: {}", username, authResponse.getMessage());

                response.reset();
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Content-Type", "text/html;charset=UTF-8");

                String html = generateLoginPageWithError(clientId, responseType, redirectUri, scope, state, authResponse.getMessage());
                byte[] bytes = html.getBytes("UTF-8");
                response.setContentLength(bytes.length);
                response.getOutputStream().write(bytes);
                response.getOutputStream().flush();
                return;
            }

        } catch (Exception e) {
            logger.error("登录处理异常", e);
            response.reset();
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Content-Type", "text/html;charset=UTF-8");

            String html = generateLoginPageWithError(clientId, responseType, redirectUri, scope, state, "登录服务异常");
            byte[] bytes = html.getBytes("UTF-8");
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
            return;
        }
    }

    /**
     * 显示授权确认页面
     *
     * @param clientId 客户端ID
     * @param responseType 响应类型
     * @param redirectUri 重定向URI
     * @param scope 作用域
     * @param state 状态参数
     * @param response HTTP响应
     * @return 授权确认页面HTML
     */
    @GetMapping("/authorize/confirm")
    @ResponseBody
    public String authorizeConfirm(
            @RequestParam("client_id") String clientId,
            @RequestParam("response_type") String responseType,
            @RequestParam("redirect_uri") String redirectUri,
            @RequestParam(value = "scope", required = false) String scope,
            @RequestParam(value = "state", required = false) String state,
            HttpServletResponse response) {

        logger.info("显示授权确认页面，客户端ID: {}", clientId);

        // 设置响应编码 - 确保中文正确显示
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");

        return generateAuthorizePage(clientId, responseType, redirectUri, scope, state);
    }

    /**
     * 处理授权确认
     *
     * @param approved 是否同意授权
     * @param clientId 客户端ID
     * @param responseType 响应类型
     * @param redirectUri 重定向URI
     * @param scope 作用域
     * @param state 状态参数
     * @param request HTTP请求
     * @param response HTTP响应
     * @return 授权结果
     */
    @PostMapping("/authorize/confirm")
    public String authorizeConfirm(
            @RequestParam("approved") boolean approved,
            @RequestParam("client_id") String clientId,
            @RequestParam("response_type") String responseType,
            @RequestParam("redirect_uri") String redirectUri,
            @RequestParam(value = "scope", required = false) String scope,
            @RequestParam(value = "state", required = false) String state,
            HttpServletRequest request,
            HttpServletResponse response,
            Model model) throws IOException {

        try {
            logger.info("处理授权确认，客户端ID: {}, 同意: {}", clientId, approved);

            if (approved) {
                // 用户同意授权
                HttpSession session = request.getSession();
                SSOUser user = (SSOUser) session.getAttribute("user");

                if (user == null) {
                    // 用户未登录，重定向到登录页面
                    return "redirect:/sso/login?client_id=" + clientId +
                            "&response_type=" + responseType +
                            "&redirect_uri=" + redirectUri +
                            (scope != null ? "&scope=" + scope : "") +
                            (state != null ? "&state=" + state : "");
                }

                // 生成授权码
                SSORequest ssoRequest = new SSORequest();
                ssoRequest.setClientId(clientId);
                ssoRequest.setRedirectUri(redirectUri);
                ssoRequest.setClientSecret(clientId);
                ssoRequest.setScope(scope);
                ssoRequest.setState(state);
                ssoRequest.setUsername(user.getUsername());

                String code = ssoAuthService.generateAuthorizationCode(ssoRequest);

                // 重定向到客户端
                String redirectUrl = redirectUri + "?code=" + code;
                if (state != null) {
                    redirectUrl += "&state=" + state;
                }

                logger.info("授权成功，重定向到: {}", redirectUrl);
                response.sendRedirect(redirectUrl);
                return null;

            } else {
                // 用户拒绝授权
                String errorUrl = redirectUri + "?error=" + SSOConstants.ERROR_ACCESS_DENIED +
                        "&error_description=用户拒绝授权";
                if (state != null) {
                    errorUrl += "&state=" + state;
                }

                logger.info("用户拒绝授权，重定向到: {}", errorUrl);
                response.sendRedirect(errorUrl);
                return null;
            }

        } catch (Exception e) {
            logger.error("授权确认处理异常", e);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            return generateAuthorizePageWithError(clientId, responseType, redirectUri, scope, state, "授权处理异常");
        }
    }

    /**
     * 单点登出
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @return 登出结果
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            HttpSession session = request.getSession();
            SSOUser user = (SSOUser) session.getAttribute("user");

            if (user != null) {
                logger.info("用户登出，用户ID: {}", user.getUserId());

                // 执行登出
                ssoAuthService.logout(user.getUserId());

                // 清除会话
                session.invalidate();
            }

            // 重定向到登录页面
            response.sendRedirect("/sso/login");
            return null;

        } catch (Exception e) {
            logger.error("登出处理异常", e);
            response.sendRedirect("/sso/login");
            return null;
        }
    }

    /**
     * 检查登录状态
     *
     * @param request HTTP请求
     * @return 登录状态
     */
    @GetMapping("/status")
    @ResponseBody
    public SSOResponse checkStatus(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                SSOUser user = (SSOUser) session.getAttribute("user");
                if (user != null) {
                    return SSOResponse.success("用户已登录", user, null);
                }
            }

            return SSOResponse.error(401, "用户未登录");

        } catch (Exception e) {
            logger.error("检查登录状态异常", e);
            return SSOResponse.error(500, "检查登录状态异常");
        }
    }

    /**
     * 生成登录页面HTML
     */
    private String generateLoginPage(String clientId, String responseType, String redirectUri, String scope, String state) {
        return generateLoginPageWithError(clientId, responseType, redirectUri, scope, state, null);
    }

    /**
     * 生成带错误信息的登录页面HTML
     */
    private String generateLoginPageWithError(String clientId, String responseType, String redirectUri, String scope, String state, String error) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html lang=\"zh-CN\">");
        html.append("<head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
        html.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        html.append("<title>SSO登录</title>");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }");
        html.append(".login-container { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 400px; }");
        html.append(".login-header { text-align: center; margin-bottom: 30px; }");
        html.append(".login-header h1 { color: #333; margin: 0; }");
        html.append(".form-group { margin-bottom: 20px; }");
        html.append(".form-group label { display: block; margin-bottom: 5px; color: #555; font-weight: bold; }");
        html.append(".form-group input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px; box-sizing: border-box; }");
        html.append(".form-group input:focus { outline: none; border-color: #007bff; }");
        html.append(".login-button { width: 100%; padding: 12px; background-color: #007bff; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }");
        html.append(".login-button:hover { background-color: #0056b3; }");
        html.append(".error-message { color: #dc3545; margin-top: 10px; text-align: center; }");
        html.append(".client-info { background-color: #f8f9fa; padding: 15px; border-radius: 4px; margin-bottom: 20px; font-size: 14px; color: #666; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div class=\"login-container\">");
        html.append("<div class=\"login-header\"><h1>单点登录</h1></div>");
        html.append("<div class=\"client-info\">");
        html.append("<strong>客户端信息：</strong><br>");
        html.append("客户端ID: ").append(clientId).append("<br>");
        html.append("重定向URI: ").append(redirectUri);
        html.append("</div>");
        html.append("<form method=\"post\" action=\"/sso/login\">");
        html.append("<input type=\"hidden\" name=\"client_id\" value=\"").append(clientId).append("\">");
        html.append("<input type=\"hidden\" name=\"response_type\" value=\"").append(responseType).append("\">");
        html.append("<input type=\"hidden\" name=\"redirect_uri\" value=\"").append(redirectUri).append("\">");
        if (scope != null) {
            html.append("<input type=\"hidden\" name=\"scope\" value=\"").append(scope).append("\">");
        }
        if (state != null) {
            html.append("<input type=\"hidden\" name=\"state\" value=\"").append(state).append("\">");
        }
        html.append("<div class=\"form-group\">");
        html.append("<label for=\"username\">用户名：</label>");
        html.append("<input type=\"text\" id=\"username\" name=\"username\" required>");
        html.append("</div>");
        html.append("<div class=\"form-group\">");
        html.append("<label for=\"password\">密码：</label>");
        html.append("<input type=\"password\" id=\"password\" name=\"password\" required>");
        html.append("</div>");
        html.append("<button type=\"submit\" class=\"login-button\">登录</button>");
        if (error != null) {
            html.append("<div class=\"error-message\">").append(error).append("</div>");
        }
        html.append("</form>");
        html.append("</div>");
        html.append("</body>");
        html.append("</html>");
        return html.toString();
    }

    /**
     * 生成授权确认页面HTML
     */
    private String generateAuthorizePage(String clientId, String responseType, String redirectUri, String scope, String state) {
        return generateAuthorizePageWithError(clientId, responseType, redirectUri, scope, state, null);
    }

    /**
     * 生成带错误信息的授权确认页面HTML
     */
    private String generateAuthorizePageWithError(String clientId, String responseType, String redirectUri, String scope, String state, String error) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html lang=\"zh-CN\">");
        html.append("<head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        html.append("<title>授权确认</title>");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }");
        html.append(".authorize-container { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 500px; }");
        html.append(".authorize-header { text-align: center; margin-bottom: 30px; }");
        html.append(".authorize-header h1 { color: #333; margin: 0; }");
        html.append(".client-info { background-color: #f8f9fa; padding: 20px; border-radius: 4px; margin-bottom: 30px; }");
        html.append(".client-info h3 { margin-top: 0; color: #333; }");
        html.append(".permission-list { margin: 20px 0; }");
        html.append(".permission-list ul { list-style: none; padding: 0; }");
        html.append(".permission-list li { padding: 8px 0; border-bottom: 1px solid #eee; }");
        html.append(".permission-list li:last-child { border-bottom: none; }");
        html.append(".button-group { display: flex; gap: 15px; justify-content: center; }");
        html.append(".btn { padding: 12px 30px; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; text-decoration: none; display: inline-block; text-align: center; }");
        html.append(".btn-primary { background-color: #007bff; color: white; }");
        html.append(".btn-primary:hover { background-color: #0056b3; }");
        html.append(".btn-secondary { background-color: #6c757d; color: white; }");
        html.append(".btn-secondary:hover { background-color: #545b62; }");
        html.append(".error-message { color: #dc3545; margin-top: 10px; text-align: center; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div class=\"authorize-container\">");
        html.append("<div class=\"authorize-header\"><h1>授权确认</h1></div>");
        html.append("<div class=\"client-info\">");
        html.append("<h3>应用请求访问您的账户</h3>");
        html.append("<p><strong>客户端ID：</strong>").append(clientId).append("</p>");
        html.append("<p><strong>重定向URI：</strong>").append(redirectUri).append("</p>");
        if (scope != null) {
            html.append("<p><strong>作用域：</strong>").append(scope).append("</p>");
        }
        html.append("</div>");
        html.append("<div class=\"permission-list\">");
        html.append("<h4>该应用将获得以下权限：</h4>");
        html.append("<ul>");
        html.append("<li>读取您的基本信息</li>");
        html.append("<li>访问您的账户数据</li>");
        html.append("<li>代表您执行操作</li>");
        html.append("</ul>");
        html.append("</div>");
        html.append("<form method=\"post\" action=\"/sso/authorize/confirm\">");
        html.append("<input type=\"hidden\" name=\"client_id\" value=\"").append(clientId).append("\">");
        html.append("<input type=\"hidden\" name=\"response_type\" value=\"").append(responseType).append("\">");
        html.append("<input type=\"hidden\" name=\"redirect_uri\" value=\"").append(redirectUri).append("\">");
        if (scope != null) {
            html.append("<input type=\"hidden\" name=\"scope\" value=\"").append(scope).append("\">");
        }
        if (state != null) {
            html.append("<input type=\"hidden\" name=\"state\" value=\"").append(state).append("\">");
        }
        html.append("<div class=\"button-group\">");
        html.append("<button type=\"submit\" name=\"approved\" value=\"true\" class=\"btn btn-primary\">同意授权</button>");
        html.append("<button type=\"submit\" name=\"approved\" value=\"false\" class=\"btn btn-secondary\">拒绝授权</button>");
        html.append("</div>");
        if (error != null) {
            html.append("<div class=\"error-message\">").append(error).append("</div>");
        }
        html.append("</form>");
        html.append("</div>");
        html.append("</body>");
        html.append("</html>");
        return html.toString();
    }





}
